package aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TransactionAspect {
    private static final Logger log= LoggerFactory.getLogger(TransactionAspect.class);

    @Pointcut("execution(* service..*.*(..))")
    public void pt(){

    }

    @Before(value = "pt()")
    public void before(JoinPoint jp){
        log.info("TransactionAspect前置增强模拟打开数据库连接并开启事务");
        log.info("SqlSession sqlSession=MyBatisUtils.createSqlSession(false);");
    }

    @AfterReturning(value = "pt()",returning = "result")
    public void afterReturning(JoinPoint jp,Object result){
        log.info("TransactionAspect后置增强模拟正常完成事务提交");
        log.info("session.commit();");
    }

    @AfterThrowing(value = "pt()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Throwable e){
        log.info("TransactionAspect异常抛出增强模拟业务异常回滚事务，异常信息为："+e.getMessage());
        log.info("session.rollback()");
    }

    @After(value = "pt()")
    public void after(JoinPoint jp){
        log.info("TransactionAspect最终增强模拟业务完成释放资源");
        log.info("MyBatisUtils.closeSqlSession(sqlSession);");
    }
}
